using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using P10_StudentManage.Data;
using P10_StudentManage.Models;

namespace P10_StudentManage;

public partial class Form1 : Form
{
    private readonly GradeContext _context = new GradeContext();
    private BindingList<Grade> _grades;
    private int _selectedGradeId;

    public Form1()
    {
        InitializeComponent();
    }

    private async void Form1_Load(object sender, EventArgs e)
    {
        await LoadGrades();
    }

    private async Task LoadGrades()
    {
        _grades = new BindingList<Grade>(await _context.Grades.ToListAsync());
        dataGridViewGrades.DataSource = _grades;
    }

    private async void btnAdd_Click(object? sender, EventArgs e)
    {
        //检查输入内容
        int score;
        if (string.IsNullOrWhiteSpace(txtName.Text) || !int.TryParse(txtScore.Text,out score) || string.IsNullOrWhiteSpace(txtSubject.Text))
        {
            MessageBox.Show("Please enter a valid value");
            return;
        }

        var newGrade = new Grade()
        {
            StudentName = txtName.Text,
            Score = score,
            Subject = txtSubject.Text
        };
        _context.Grades.Add(newGrade);
        await _context.SaveChangesAsync();
        await LoadGrades(); // 刷新 DataGridView
        ClearInputFields();
    }

    private void ClearInputFields()
    {
        txtName.Text = string.Empty;
        txtSubject.Text = string.Empty;
        txtScore.Text = string.Empty;
    }

    private void dataGridViewGrades_SelectionChanged(object sender, EventArgs e)
    {
        if (dataGridViewGrades.SelectedRows.Count>0)
        {
            // 获取当前选中的行
            DataGridViewRow selectedRow = dataGridViewGrades.SelectedRows[0];
            // 将选中的行的数据填充到 TextBox 中
            txtName.Text = selectedRow.Cells["StudentName"].Value?.ToString();
            txtSubject.Text = selectedRow.Cells["Subject"].Value?.ToString();
            txtScore.Text = selectedRow.Cells["Score"].Value?.ToString();
            
            if (selectedRow.Cells["Id"].Value != null && int.TryParse(selectedRow.Cells["Id"].Value.ToString(), out int selectedId))
            {
                // 可以将 selectedId 存储在一个窗体级别的变量中
                _selectedGradeId = selectedId;
            }
        }
    }

    private async void btnUpdate_Click(object? sender, EventArgs e)
    {
        if (_selectedGradeId == -1)
        {
            MessageBox.Show("请先在表格中选择要修改的记录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtSubject.Text) || !int.TryParse(txtScore.Text, out int score))
        {
            MessageBox.Show("请填写完整且正确的学生信息和成绩。", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        var gradeToUpdate = await _context.Grades.FindAsync(_selectedGradeId);

        if (gradeToUpdate != null)
        {
            gradeToUpdate.StudentName = txtName.Text;
            gradeToUpdate.Subject = txtSubject.Text;
            gradeToUpdate.Score = score;

            try
            {
                await _context.SaveChangesAsync();
                await LoadGrades(); // 刷新 DataGridView
                ClearInputFields();
                _selectedGradeId = -1; // 重置选中的 Id
                MessageBox.Show("学生成绩修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (DbUpdateException ex)
            {
                MessageBox.Show($"修改学生成绩失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            MessageBox.Show("找不到要修改的学生成绩记录。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private async void btnDelete_Click(object? sender, EventArgs e)
    {
        if (_selectedGradeId == -1)
        {
            MessageBox.Show("请先在表格中选择要修改的记录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        var gradeToDelete = await _context.Grades.FindAsync(_selectedGradeId);
        if (gradeToDelete != null)
        {
            _context.Grades.Remove(gradeToDelete);
            await _context.SaveChangesAsync();
            await LoadGrades();
            ClearInputFields();
            _selectedGradeId = -1;
            MessageBox.Show("<UNK>", "<UNK>", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        
    }
}